const QQMapWx = require("./qqmap-wx-jssdk");
const secretKey = "gbMZdPIrHewUYaA3awUClJ4mebegcYpU";
const instance = new QQMapWx({
  key: 'RSFBZ-K5H3P-QK7DF-LSXWV-2U45K-TZF7H'
});

let request = (method, options) => {
  options = options || {};
  let opts = {
    sig: secretKey,
  };
  return new Promise(ps => {
    options = {
      ...opts,
      success: res => {
        let { status, result } = res;
        if (status != 0) {
          console.log(res);
          ps(false);
          return;
        }
        ps(result);
      },
      fail: error => {
        ps(false);
        console.error(error)
      },
      ...options
    }
    instance[method](
      {
        ...options
      }
    )
  })
}
/**
 * 经纬度转换成地址
 * @param {string} latitude 经度 
 * @param {string} longitude 纬度
 */
let reverseGeocoder = async (latitude, longitude) => {
  let opts = {
    location: {
      latitude,
      longitude
    },
  }
  let ret = await request('reverseGeocoder', opts);
  return ret;
}
/**
 * 获取城市列表 
 */
let getCityList = async () => {
  let method = "getCityList";
  let ret = await request(method);
  return ret;
}
let setCity = (name) => {
  wx.setStorageSync('city', name);
}
let getCity = () => {
  return wx.getStorageSync('city');
}
/**
 * 检查是否授权获取位置信息
 */
let checkLocationAuth = () => {
  return new Promise(ps => {
    wx.getSetting({
      success: res => {
        let hasAuth = res.authSetting["scope.userLocation"];
        ps(hasAuth && true);
      }, fail: (error) => {
        ps(false);
        console.error(error)
      }
    })
  });
}
export let setLocationStorage = local => {
  wx.setStorageSync('local', local);
}
export let getLocationStorage = () => {
  return wx.getStorageSync("local");
}
export { reverseGeocoder, getCityList, setCity, getCity, checkLocationAuth };